﻿using B.S.Meeting.Domain;
using B.S.Meeting.ErrorCode;
using B.S.Meeting.Infrastructure.Interfaces;
using B.S.Meeting.WriteAPI.Applications.Commands.Depts;
using MediatR;

namespace B.S.Meeting.WriteAPI.Applications.CommandHandlers.Depts
{
    public class UpdDeptCommandHandler : IRequestHandler<UpdDeptCommand, APIResult<int>>
    {
        IBaseRepository<Dept> dRep;
        ILogger<UpdDeptCommandHandler> logger;

        public UpdDeptCommandHandler(IBaseRepository<Dept> dRep, ILogger<UpdDeptCommandHandler> logger)
        {
            this.dRep = dRep;
            this.logger = logger;
        }

        public async Task<APIResult<int>> Handle(UpdDeptCommand request, CancellationToken cancellationToken)
        {
            try
            {
                var dept = await dRep.GetByIdAsync(request.DeptId);
                if (dept == null)
                {
                    logger.LogWarning($"未找到ID为 {request.DeptId} 的部门");
                    return new APIResult<int>
                    {
                        Code = StatusEnumCode.Fail,
                        Message = "未找到指定的部门",
                        Data = 0
                    };
                }

                // 更新部门名称和部门描述
                dept.DeptName = request.DeptName;
                dept.DeptDesc = request.DeptDesc;
                dept.UserId = request.UserId;
                dept.ParentId = request.ParentId;

                var res = await dRep.UpdAsync(dept);
                logger.LogInformation($"成功更新部门的上级ID： {request.ParentId}, 名称: {request.DeptName},描述：{request.DeptDesc}");

                return new APIResult<int>
                {
                    Code = StatusEnumCode.Ok,
                    Message = "修改部门成功",
                    Data = res
                };
            }
            catch (Exception)
            {

                throw;
            }
        }
    }
}
